//
//  HLDownLoaderManager.m
//  HLDownLoader
//
//  Created by hulian-ios on 17/9/16.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLDownLoaderManager.h"
#import "NSString+DownLoader.h"

@interface HLDownLoaderManager()<NSCopying, NSMutableCopying>

@end

@implementation HLDownLoaderManager

static HLDownLoaderManager *_shareInstance;

+ (instancetype)shareInstance
{
    if (_shareInstance == nil) {
        _shareInstance = [[self alloc] init];
    }
    return _shareInstance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (!_shareInstance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _shareInstance = [super allocWithZone:zone];
        });
    }
    return _shareInstance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _shareInstance;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    return _shareInstance;
}

// key: md5(url)  value: HLDownLoader
- (NSMutableDictionary *)downLoadInfo
{
    if (!_downLoadInfo) {
        _downLoadInfo = [NSMutableDictionary dictionary];
    }
    return _downLoadInfo;
}


- (void)hl_downLoader:(NSURL *)url downLoadInfo:(DownLoadInfoType)downLoadInfo progress:(ProgressBlockType)progressBlock success:(SuccessBlockType)successBlock failed:(FailedBlockType)failedBlock
{
    NSString *urlMD5 = [url.absoluteString md5];
    
    HLDownLoader *downLoader = self.downLoadInfo[urlMD5];
    if (downLoader == nil) {
        @synchronized (self) {
            downLoader = [[HLDownLoader alloc] init];
            self.downLoadInfo[urlMD5] = downLoader;

        }
    }
    __weak typeof(self) weakSelf = self;
    [downLoader hl_downLoader:url downLoadInfo:downLoadInfo progress:progressBlock success:^(NSString *filePath) {
        @synchronized (self) {
            [weakSelf.downLoadInfo removeObjectForKey:urlMD5];
        }
        // 拦截block
        successBlock(filePath);
    } failed:failedBlock];
}


- (void)pauseWithURL:(NSURL *)url
{
    NSString *urlMD5 = [url.absoluteString md5];
    HLDownLoader *downLoader = self.downLoadInfo[urlMD5];
    [downLoader pauseCurrentTask];
}

- (void)resumeWithURL:(NSURL *)url
{
    NSString *urlMD5 = [url.absoluteString md5];
    HLDownLoader *downLoader = self.downLoadInfo[urlMD5];
    [downLoader resumeCurrentTask];
}
- (void)cancelWithURL:(NSURL *)url
{
    NSString *urlMD5 = [url.absoluteString md5];
    HLDownLoader *downLoader = self.downLoadInfo[urlMD5];
    [downLoader cacelCurrentTask];
}


- (void)pauseAll
{
    [self.downLoadInfo.allValues makeObjectsPerformSelector:@selector(pauseCurrentTask) withObject:nil];
}

- (void)resumeAll
{
    [self.downLoadInfo.allValues makeObjectsPerformSelector:@selector(resumeCurrentTask) withObject:nil];

}

@end
